package com.common.util.web.directive;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.common.util.web.ContextHolder;
import com.github.pagehelper.PageInfo;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

public class PageNavigatorDirective implements TemplateDirectiveModel {
	public static final Logger logger = LoggerFactory.getLogger(PageNavigatorDirective.class);
	private List<String> excludeReqParams = new ArrayList() {
		private static final long serialVersionUID = 8330080263534294807L;
	};

	public void execute(Environment env, Map params, TemplateModel[] templateModels,
			TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
		HttpServletRequest request = ContextHolder.getRequest();
		PageInfo<?> pageInfo = getPageInfo(params);
		if (pageInfo == null) {
			return;
		}
		System.out.println(pageInfo.toString());

		boolean isPost = DirectiveUtils.getBool("post", true, params).booleanValue();

		StringBuffer pageBar = new StringBuffer();
		pageBar.append("<form id='pager' name='pager' action='" + getRequestPath(request)
				+ (isPost ? "" : getQueryString(request)) + "' method='" + (isPost ? "post" : "get") + "'>\n");
		pageBar.append("<input id='pageNum' name='pageNum' type='hidden' value='" + pageInfo.getPageNum() + "' />\n");
		pageBar.append(
				"<input id='pageSize' name='pageSize' type='hidden' value='" + pageInfo.getPageSize() + "' />\n");
		if (isPost) {
			String paramName = null;
			String[] paramValues = null;
			for (Enumeration<String> paramNames = request.getParameterNames(); paramNames.hasMoreElements();) {
				paramName = (String) paramNames.nextElement();
				if (excludedParam(paramName)) {
					logger.info("排除参数={},排除参数列表={}", paramName, this.excludeReqParams);
				} else {
					paramValues = request.getParameterValues(paramName);
					String[] arrayOfString1;
					int j = (arrayOfString1 = paramValues).length;
					for (int i = 0; i < j; i++) {
						String paramValue = arrayOfString1[i];
						pageBar.append("<input name='" + paramName + "' type='hidden' value='" + paramValue + "'/> \n");
					}
				}
			}
		}
		pageBar.append("<div class='ui horizontal statistic'><div class='label'>" + pageInfo.getTotal() + "条，共"
				+ pageInfo.getPages() + "页&nbsp;&nbsp;</div></div>");

		int navigatePages = pageInfo.getNavigatePages();
		pageBar.append("<div class='ui basic buttons'>\n");
		pageBar.append(
				"<input type='button' class='ui button' value='首页' onclick=\"javascript:document.pager.pageNum.value='1';document.pager.submit();return false;\" />\n");

		int[] navigatepageNums = pageInfo.getNavigatepageNums();
		for (int i = 0; i < navigatepageNums.length; i++) {
			if (pageInfo.getPageNum() == navigatepageNums[i]) {
				pageBar.append(
						"<input type='button' onclick=\"javascript:document.pager.pageNum.value='" + navigatepageNums[i]
								+ "';document.pager.submit();return false;\" class='ui blue basic button' value='"
								+ navigatepageNums[i] + "' />\n");
			} else {
				pageBar.append("<input type='button' onclick=\"javascript:document.pager.pageNum.value='"
						+ navigatepageNums[i] + "';document.pager.submit();return false;\" class='ui button' value='"
						+ navigatepageNums[i] + "' />\n");
			}
		}
		pageBar.append(
				"<input type='button' class='ui button' value='尾页' onclick=\"javascript:document.pager.pageNum.value='"
						+ pageInfo.getPages() + "';document.pager.submit();return false;\" />\n");
		pageBar.append("</div>\n");
		pageBar.append("</form>");
		env.getOut().write(pageBar.toString());
	}

	private boolean excludedParam(String paramName) {
		return this.excludeReqParams.contains(paramName.toLowerCase());
	}

	private PageInfo<?> getPageInfo(Map params) {
		return (PageInfo) ContextHolder.getRequest().getAttribute("pageInfo");
	}

	private String getRequestPath(HttpServletRequest request) {
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
		String requestUri = request.getRequestURI();
		return basePath + ((requestUri != null) && (!"".equals(requestUri)) ? requestUri : "");
	}

	private String getQueryString(HttpServletRequest request) {
		String queryString = request.getQueryString();
		return (queryString != null) && (!"".equals(queryString)) ? "?" + queryString : "";
	}
}
